import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { CartItem, Dish } from '@/types';
import { getUserCart, addToCart, updateCartItem, deleteCartItem, clearUserCart } from '@/api/cart';
import { getDishById } from '@/api/dish';
import { ElMessage } from 'element-plus';
import { useUserStore } from './user';

export const useCartStore = defineStore('cart', () => {
  // 状态
  const cartItems = ref<CartItem[]>([]);
  const loading = ref(false);

  // 计算属性
  const cartCount = computed(() => {
    return cartItems.value.reduce((total, item) => total + item.quantity, 0);
  });

  const totalAmount = computed(() => {
    return cartItems.value.reduce((total, item) => {
      if (item.dish) {
        return total + item.dish.dishPrice * item.quantity;
      }
      return total;
    }, 0);
  });

  // 加载购物车
  const loadCart = async (userId: number) => {
    loading.value = true;
    try {
      const response = await getUserCart(userId);
      if (response.operateResult === 'SUCC' && response.data) {
        // 加载每个购物车项的菜品信息
        const itemsWithDishes = await Promise.all(
          response.data.map(async (item) => {
            const dishRes = await getDishById(item.dishId);
            if (dishRes.operateResult === 'SUCC' && dishRes.data) {
              return { ...item, dish: dishRes.data };
            }
            return item;
          })
        );
        cartItems.value = itemsWithDishes;
      } else {
        cartItems.value = [];
      }
    } catch (error: any) {
      cartItems.value = [];
    } finally {
      loading.value = false;
    }
  };

  // 添加到购物车
  const addItem = async (userId: number, dishId: number, quantity: number = 1) => {
    try {
      // 检查购物车中是否已存在该商品
      const existingItem = cartItems.value.find(item => item.dishId === dishId);
      
      if (existingItem) {
        // 更新数量
        const newQuantity = existingItem.quantity + quantity;
        const response = await updateCartItem(existingItem.cartId!, {
          ...existingItem,
          quantity: newQuantity
        });
        
        if (response.operateResult === 'SUCC') {
          await loadCart(userId);
          ElMessage.success('已更新购物车');
          return true;
        }
      } else {
        // 添加新商品
        const response = await addToCart({
          userId,
          dishId,
          quantity
        });
        
        if (response.operateResult === 'SUCC') {
          await loadCart(userId);
          ElMessage.success('已加入购物车');
          return true;
        } else {
          ElMessage.error(response.errorMsg || '添加失败');
        }
      }
    } catch (error: any) {
      ElMessage.error(error.message || '添加失败');
      return false;
    }
  };

  // 更新购物车项数量
  const updateQuantity = async (userId: number, cartId: number, quantity: number) => {
    try {
      const item = cartItems.value.find(i => i.cartId === cartId);
      if (!item) {
        ElMessage.error('购物车项不存在');
        return false;
      }

      const response = await updateCartItem(cartId, {
        ...item,
        quantity
      });
      
      if (response.operateResult === 'SUCC') {
        await loadCart(userId);
        return true;
      } else {
        ElMessage.error(response.errorMsg || '更新失败');
        return false;
      }
    } catch (error: any) {
      ElMessage.error(error.message || '更新失败');
      return false;
    }
  };

  // 删除购物车项
  const removeItem = async (userId: number, cartId: number) => {
    try {
      const response = await deleteCartItem(cartId);
      if (response.operateResult === 'SUCC') {
        await loadCart(userId);
        ElMessage.success('已删除');
        return true;
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
        return false;
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
      return false;
    }
  };

  // 清空购物车
  const clearCart = async (userId: number) => {
    try {
      const response = await clearUserCart(userId);
      if (response.operateResult === 'SUCC') {
        cartItems.value = [];
        ElMessage.success('购物车已清空');
        return true;
      } else {
        ElMessage.error(response.errorMsg || '清空失败');
        return false;
      }
    } catch (error: any) {
      ElMessage.error(error.message || '清空失败');
      return false;
    }
  };

  return {
    cartItems,
    loading,
    cartCount,
    totalAmount,
    loadCart,
    addItem,
    updateQuantity,
    removeItem,
    clearCart
  };
});

